package com.hzchendou.blog.demo.auth.security;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * @Date: 2022-05-21 22:47
 * @since: 1.0
 */
public class AuthClientCredentialsTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter {
    private AuthenticationEntryPoint authenticationEntryPoint;

    private final AuthorizationServerSecurityConfigurer configurer;

    public AuthClientCredentialsTokenEndpointFilter(
            AuthorizationServerSecurityConfigurer configurer) {
        this.configurer = configurer;
    }

    @Override
    public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
        this.authenticationEntryPoint = authenticationEntryPoint;
    }

    @Override
    protected AuthenticationManager getAuthenticationManager() {
        return configurer.and().getSharedObject(AuthenticationManager.class);
    }

    @Override
    public void afterPropertiesSet() {
        setAuthenticationFailureHandler((request, response, exception) -> authenticationEntryPoint.commence(request, response, exception));
        setAuthenticationSuccessHandler((request, response, authentication) -> {});
    }
}
